<template>
	<view>
		<nav-header title="附近的人" :showRight="false"></nav-header>
		<view>
			<view class="location">
				<uni-icons type="location" size="30" @click="getLocation"></uni-icons>
			</view>
		</view>
		<view class="friend-items">
			<up-index-list :index-list="friendIdx">
				<template v-for="(friends,i) in friendGroups">
					<up-index-item>
						<up-index-anchor :text="friendIdx[i]=='*'?'在线':friendIdx[i]"
							bgColor="#f2f3fd"></up-index-anchor>
						<view v-for="(friend,idx) in friends" :key="idx">
							<friend-item :friend="friend">
							</friend-item>
						</view>
					</up-index-item>
				</template>
			</up-index-list>
		</view>
	</view>
</template>

<script>
	import {
		pinyin
	} from 'pinyin-pro';

	export default {
		data() {
			return {
				searchText: ''
			}
		},
		methods: {
			isEnglish(character) {
				return /^[A-Za-z]+$/.test(character);
			},
			firstLetter(strText) {
				// 使用pinyin-pro库将中文转换为拼音
				let pinyinOptions = {
					toneType: 'none', // 无声调
					type: 'normal' // 普通拼音
				};
				let pyText = pinyin(strText, pinyinOptions);
				return pyText[0];
			},
			getLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: function (res) {
						console.log(res)
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
					}
				});
			}
		},
		computed: {
			friends() {
				return this.friendStore.friends;
			},
			friendGroupMap() {
				// 按首字母分组
				let groupMap = new Map();
				this.friends.forEach((f) => {
					if (this.searchText && !f.nickName.includes(this.searchText)) {
						return;
					}
					let letter = this.firstLetter(f.nickName).toUpperCase();
					// 非英文一律为#组
					if (!this.isEnglish(letter)) {
						letter = "#"
					}
					if (f.online) {
						letter = '*'
					}
					if (groupMap.has(letter)) {
						groupMap.get(letter).push(f);
					} else {
						groupMap.set(letter, [f]);
					}
				})
				// 排序
				let arrayObj = Array.from(groupMap);
				arrayObj.sort((a, b) => {
					// #组在最后面
					if (a[0] == '#' || b[0] == '#') {
						return b[0].localeCompare(a[0])
					}
					return a[0].localeCompare(b[0])
				})
				groupMap = new Map(arrayObj.map(i => [i[0], i[1]]));
				return groupMap;
			},
			friendIdx() {
				return Array.from(this.friendGroupMap.keys());
			},
			friendGroups() {
				return Array.from(this.friendGroupMap.values());
			}
		}
	}
</script>

<style lang="less" scoped>
	.location {
		padding: 20rpx;
	}
	.friend-items {
		flex: 1;
		padding: 0;
		border: #dddddd solid 1px;
		overflow: hidden;
		position: relative;
	
		.scroll-bar {
			height: 100%;
		}
	}
</style>